package menu

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"fmt"
	"google.golang.org/grpc/codes"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserListMenuLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserListMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListMenuLogic {
	return &UserListMenuLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserListMenuLogic) UserListMenu(req *types.UserMenuReq) (*types.MenuList, error) {
	var resp types.MenuList
	query := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityMenu{}).
		Joins("menu").
		Joins(fmt.Sprintf("LEFT JOIN %s topic ON topic.menu_id = menu.id", model.TableNameCsCommunityTopic))

	// 只查询已发布的专栏
	query = query.Where("menu.publish = ?", types.MenuStatusPublish)

	if err := query.Order("menu.id ASC").Select("menu.*", "COUNT(topic.id) topic_count").Group("menu.id").Find(&resp.Data).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	// 批量查询每个专栏下的topics

	for _, menu := range resp.Data {
		topicQuery := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityTopic{}).
			Joins("topic").
			Joins(fmt.Sprintf("LEFT JOIN %s post ON post.topic_id = topic.id", model.TableNameCsCommunityPost)).
			Select(
				"topic.id", "topic.name", "topic.image_url", "topic.description",
				"topic.menu_id", "topic.type",
				fmt.Sprintf("CASE WHEN topic.type = %d THEN 1 END disabled", types.TopicTypeForbidden),
				"IFNULL(COUNT(DISTINCT post.id), 0) as post_count",
				"IFNULL(SUM(post.view_count), 0) as view_count",
			).
			Where("topic.menu_id = ?", menu.Id).
			Order("topic.id ASC").
			Group("topic.id")

		if err := topicQuery.Find(&menu.Topics).Error; err != nil {
			return nil, e.NewGrpcErr(codes.Internal, e.DBError)
		}
	}

	return &resp, nil
}
